//
//  MiaoSha_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//


/*
 owner:cy
 update:2017年01月17日17:43:56
 info: 秒杀模块
 */
import RxSwift
import UtilCore

class MiaoSha_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var miaoSha_Tv: UITableView!
    
    @IBOutlet weak var filter_Cv: UICollectionView!
    
    @IBOutlet weak var time_Lb: CountDownLabel!
    @IBOutlet weak var time_desc_Lb: UILabel!
    
    @IBOutlet weak var header_Desc_Lb: UILabel!
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    var id:String?
    var manageVm:MiaoSha_Vm?
    ///倒计时
    var countDown = CountDown()
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    var miaoShaItems = [MiaoShaModel]() {
        didSet {
            if miaoShaItems.count > 0 {
                for (index,item)  in miaoShaItems.enumerated() {
                    if item.active == 1 {
                        self.currentItem = item
                        self.filter_Cv.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true)
                    }
                }
                if self.currentItem == nil {
                    self.currentItem = miaoShaItems[0]
                    self.filter_Cv.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredHorizontally, animated: true)
                }
                
            }
            
        }
    }
    var currentItem:MiaoShaModel?{
        didSet{
            if let currentItem = self.currentItem {
                self.filter_Cv.reloadData()
                self.miaoSha_Tv.reloadData()
                if currentItem.item_state == 3 {
                    self.time_Lb.isHidden = false
                    self.time_desc_Lb.isHidden = false
                    self.time_Lb.timerInterval = currentItem.lefttime
                    self.header_Desc_Lb.textColor = UIColor(hex: "333333")
                }else{
                    self.time_Lb.isHidden = true
                    self.time_desc_Lb.isHidden = true
                    self.header_Desc_Lb.textColor = UIColor(hex: "e31436")
                }
                self.header_Desc_Lb.text = currentItem.header_desc
                
                
            }
        }
    }
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.countDown.deinitTimer()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(MiaoSha_Vc.headerRefresh))
        self.miaoSha_Tv.mj_header = header
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        let refreshTriger = Observable.of(
            rx.sentMessage(#selector(MiaoSha_Vc.headerRefresh)).map { _ in () },
            Observable.just().map { _ in () }
            )
            .merge()
        self.manageVm = MiaoSha_Vm(refreshTriger: refreshTriger.filter{ _ in
            self.id != nil
            }.map{self.id!})
        self.manageVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.manageVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.manageVm?
            .miaoShaList
            .subscribe(onNext: { [unowned self] ( item ) in
                self.miaoShaItems = item
                self.startCountDown()
            })
            .disposed(by: disposeBag)
    }
}
extension MiaoSha_Vc{
    /// 开始倒计时
    func startCountDown() {
        self.countDown.countDownWith_Block{[unowned self] _ in
            for item in self.miaoShaItems{
                if item.lefttime > 0{
                    if Int(item.lefttime) == 1{
                        ///发起重新加载数据
                        self.requestToRefresh()
                    }
                    item.lefttime = item.lefttime - 1
                }
            }
        }
    }
    ///重新刷新界面
    func requestToRefresh()  {
        DispatchQueue.main.async {
            self.manageVm?.reloadTrigger.onNext()
        }
    }
    // 顶部刷新
    func headerRefresh(){
        self.miaoSha_Tv.mj_header.endRefreshing()
        
    }
}
// MARK: UITableViewDelegate
extension MiaoSha_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if let item = self.currentItem {
            return item.arr.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let currentItem = self.currentItem!
        if currentItem.item_state == 3{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MiaoSha_TCell", for: indexPath) as! MiaoSha_TCell
            let model = self.currentItem!.arr[indexPath.row]
            cell.item = model
            cell.tap_Block = { _ in
                _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MiaoSha_Active_TCell", for: indexPath) as! MiaoSha_Active_TCell
            let model = self.currentItem!.arr[indexPath.row]
            cell.item = model
            cell.tap_Block = { _ in
                _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
            }
            return cell
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
}
// MARK: UITableViewDelegate
extension MiaoSha_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true)
        let model = self.currentItem!.arr[indexPath.row]
        _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 125
    }
    
}
// MARK: - UICollectionViewDataSource
extension MiaoSha_Vc:UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.miaoShaItems.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let item = self.miaoShaItems[indexPath.row]
        if let serverTime = item.serverTime {
            if serverTime.isToday {
                //表示是今天
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MiaoSha_Header_CCell", for: indexPath) as! MiaoSha_Header_CCell
                let item = self.miaoShaItems[indexPath.row]
                cell.updateState(isSelected: item.isEqual(item: self.currentItem!))
                cell.item = item
                return cell
            }else{
                /// 这块表示 要显示 日期
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MiaoSha_Day_Header_CCell", for: indexPath) as! MiaoSha_Day_Header_CCell
                let item = self.miaoShaItems[indexPath.row]
                cell.updateState(isSelected: item.isEqual(item: self.currentItem!))
                cell.item = item
                return cell
            }
        }else{
            //表示转换时间错误 按照 今天的格式来显示
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MiaoSha_Header_CCell", for: indexPath) as! MiaoSha_Header_CCell
            let item = self.miaoShaItems[indexPath.row]
            cell.updateState(isSelected: item.isEqual(item: self.currentItem!))
            cell.item = item
            return cell
        }
    }
}
extension MiaoSha_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        let item = self.miaoShaItems[indexPath.row]
        self.currentItem = item
    }
}

extension MiaoSha_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return CGSize(width: 85, height: self.filter_Cv.v_hegith)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        return CGSize.zero
    }
}
